<template>
  <div>
    <h4>路由组件的进入守卫</h4>
    <p>token:{{ token }}</p>
    <div>
      <label>姓名</label>
      <input type="text" v-model="user.name" />
      <br />
      <label>电话</label>
      <input type="text" v-model="user.tel" />
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      token: "",
      user: {
        name: "",
        tel: "",
      },
    };
  },
  beforeRouteEnter(to, form, next) {
    console.log("src/views/route/CompoentEnterView.vue => beforeRouteEnter");
    let tempToken = localStorage.getItem("token");

    // 早于当前组件得实例创建之前，该函数中不能通过this获取当前得组件实例对象
    // console.log(this);
    // this.token = tempToken;

    if (tempToken === null) {
      alert("未授权，无法访问");
    } else {
      // next(true);
      // 接收回调函数是，完成得依然是放行路由后续操作
      //      传入得回调函数会在组件创建后，才被调用执行
      next(function (vm) {
        // vm 是当前组件得实例对象
        console.log("next得回调");
        vm.token = tempToken;
        let userStr = localStorage.getItem("CompoentEnterViewUser");
        localStorage.removeItem("CompoentEnterViewUser");
        vm.user = JSON.parse(userStr);
      });
    }
  },
  beforeRouteLeave(to, form, next) {
    let userStr = JSON.stringify(this.user);
    localStorage.setItem("CompoentEnterViewUser", userStr);
    next(true);
  },
  beforeCreate() {
    console.log("src/views/route/CompoentEnterView.vue => beforeCreate");
  },
  created() {
    console.log("src/views/route/CompoentEnterView.vue => created");
  },
};
</script>
